package stack;



public class LinkedListStack {

    private MyNode headNode;

    private int size;

    public void push(String data){
        MyNode newNode = new MyNode(data);
        newNode.next = headNode;
        headNode = newNode;
        size++;
    }

    public String pop(){
        if(headNode == null){
            return null;
        }
        String item = headNode.item;
        //获得头节点的下个节点
        MyNode headNext = headNode.next;
        //将下个节点赋值给头节点
        headNode = headNext;
        size--;
        return item;
    }

    /**
     * 判断栈中是否还有元素
     */
    public boolean isEmpty() {
        return size() == 0;
    }
    /**
     * 返回栈中元素个数
     */
    public synchronized int size() {
        return size;
    }

    public void print(){
        MyNode cur = headNode;
        while (cur != null){
            System.out.println(cur.item + " ");
            cur = cur.next;
        }
    }

    public static void main(String[] args) {
        LinkedListStack linkedListStack = new LinkedListStack();
        linkedListStack.push("111");
        linkedListStack.push("2222");
        linkedListStack.push("3333");
        System.out.println( linkedListStack.pop());
        System.out.println( linkedListStack.pop());
        System.out.println( linkedListStack.pop());
        System.out.println( linkedListStack.pop());
        linkedListStack.print();
    }

    private static class MyNode{

        String item;

        MyNode next;

        public MyNode(String item){
            this.item = item;
        }

    }
}
